package org.monster.context.core.file;

import org.monster.context.servlet.ServletContainer;
import org.monster.context.util.StringUtils;
import org.monster.context.util.URIUtils;

import javax.servlet.http.HttpServlet;
import java.io.File;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 文件移除命令
 *
 * @author Monster
 */
public class FileRemoveCommand implements FileCommand {

    /**
     * 日志器
     */
    private static final Logger logger = Logger.getLogger(FileAddCommand.class.getName());

    /**
     * 服务者容器
     */
    private final ServletContainer container = ServletContainer.getContainer();

    /**
     * 检查
     *
     * @param file        文件
     * @param set         文件集合
     * @param catalog     目录
     * @param fileInvoker 调用器
     */
    @Override
    public void check(File file, FileSet set, FileCatalog catalog,
                      FileInvoker fileInvoker) {
        if (set.size() < catalog.size()) {
            Set<String> keySet = catalog.keySet();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String filename = iterator.next();
                if (!set.contains(filename)) {
                    iterator.remove();
                    filename = StringUtils.keyEnds("webapps", filename);
                    String classPath = StringUtils.keyEnds("classes",
                            filename);
                    if (filename != null) {
                        filename = filename.replace("\\", "/");
                        logger.log(Level.INFO, "删除文件：" + file.getAbsolutePath());
                        String contextPath = URIUtils.startWithURI(filename);
                        String servletPath = URIUtils.allEndsWithURI(classPath);
                        if (servletPath != null) {
                            int index = servletPath.indexOf(".");
                            if (index != -1) {
                                servletPath = servletPath.substring(1, index).replace(
                                        "\\", ".");
                                HttpServlet servlet = container
                                        .getServlet(contextPath + "_" + servletPath);
                                servlet.destroy();
                            }
                        }
                    }
                }
            }
        }
    }
}
